package com.hzmg.filter;


import akka.actor.typed.Behavior;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.model.Uri;
import com.hzmg.akkacloud.common.model.WorkerInfo;
import com.hzmg.akkacloud.worker.background.ReactiveDiscoveryClient;
import com.hzmg.route.RouteDefinition;
import com.hzmg.support.uri.UriBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;

/**
 * 负载均衡过滤器
 *
 * @author Yukoo
 */
public class LoadBalancerClientFilter implements GatewayFilter, Ordered {
    private static final Logger logger = LoggerFactory.getLogger(LoadBalancerClientFilter.class);

    private static final int LOAD_BALANCE_CLIENT_ORDER = -1;

    @Override
    public int getOrder() {
        return LOAD_BALANCE_CLIENT_ORDER;
    }

    @Override
    public Behavior<Void> filter(RouteDefinition routeDefinition, GatewayFilterChain chain) {
        Uri uri = routeDefinition.getUri();
        if (uri == null || !uri.getScheme().equals("lb")) {
            return chain.filter(routeDefinition);
        }

        // 获取服务实例
        try {
            String appName = uri.getHost().toString();

            // 等待实例加载
            Thread.sleep(10000);
            WorkerInfo instance = ReactiveDiscoveryClient.getAllAliveWorkers(appName).get(0);
            logger.info("获取的实例: {}", instance);

            Uri requestUri = UriBuilder.setBuilder()
                    .scheme("http")  //TODO: safe ? https: http
                    .host(instance.getWebAddress())
//                .port(uri.getPort())
                    .build();
            routeDefinition.setUri(requestUri);

            // TODO：待完善
            HttpRequest request = HttpRequest.create(requestUri.toString());
            routeDefinition.setRequest(request);
        } catch (InterruptedException e) {
            logger.info("获取服务实例出错: {}", e);
        }

        return chain.filter(routeDefinition);
    }

}
